// TODO: search folders recursivly

// ----------------------------------------------

// TCC doesn't come with PathFindExtension
#define _TINY_C_COMPILER

#include <windows.h>
#include <stdlib.h> // EXIT_FAILURE/EXIT_SUCCESS

// ----------------------------------------------

// are we compiling with Tiny C Compiler?
#ifndef _TINY_C_COMPILER
#include <shlwapi.h>
#else

// implement PathFindExtension; I'm pretty bad at this so it's rather crude
inline LPSTR PathFindExtension(LPSTR lpcszPath)
{
  int i = lstrlen(lpcszPath);

  for (; i > 0; i--)
    if (lpcszPath[i] == '.' || lpcszPath[i] == '/' || lpcszPath[i] == '\\')
      return lpcszPath + i + 1;

  return NULL;
}

#endif

// ----------------------------------------------

inline BOOL IsFont(LPSTR lpszPath)
{
  // LUT of installable font-type extensions
  const char* c_pszFontExtension[9] = {
    "fon", "fnt", "ttf", "ttc",
    "fot", "otf", "mmm", "pfb", "pfm"
  };

  int i = 0;
  LPSTR lpszBuffer;

  // horrible ugly way of getting size of array but we don't have _countof
  for (; i < sizeof(c_pszFontExtension)/sizeof(c_pszFontExtension[0]); i++)
  {
    lpszBuffer = PathFindExtension(lpszPath);
    if (lpszBuffer != NULL)
      if (lstrcmpi(lpszBuffer, c_pszFontExtension[i]) == 0)
        return TRUE;
  }

  return FALSE;
}

// ----------------------------------------------

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCommandLine, int nShowCommand)
{
  // define variables
  HANDLE hFile;
  WIN32_FIND_DATA wfd;
  
  // none of the parameters are used..
  UNREFERENCED_PARAMETER(hInstance);
  UNREFERENCED_PARAMETER(hPrevInstance);
  UNREFERENCED_PARAMETER(lpszCommandLine);
  UNREFERENCED_PARAMETER(nShowCommand);
  
  // initialize WIN32_FIND_DATA structure
  ZeroMemory(&wfd, sizeof(wfd));
  
  // iterate through files
  hFile = FindFirstFile("res/fonts/*", &wfd);
  if (hFile != INVALID_HANDLE_VALUE)
  {
    do {
      // is it a valid font file?
      if (IsFont(wfd.cFileName))
      {
        LPSTR lpszPath = "res/fonts/";
        
        // install font
        lstrcat(lpszPath, wfd.cFileName);
        AddFontResource(lpszPath);
      }
    } while (FindNextFile(hFile, &wfd));

    CloseHandle(hFile);
  }

  return EXIT_SUCCESS;
}